package com.apes.fn.business.carAccident.modle;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.crm.business.model.InsuranceCompany;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.fileserver.File;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.plugin.soe.metadata.BusinessAttribute;
import com.apes.framework.plugin.soe.metadata.BusinessAttributeValue;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import org.springframework.util.StringUtils;

import javax.persistence.*;
import java.util.*;
import java.util.function.Consumer;

/**
 * @ClassName : CarAccident
 * @Description : 车险报案单 lossQuotation
 * @Author : WSJ
 * @Date: 2020-03-04 15:28
 */

@Getter
@Setter
@SelectBeforeUpdate
@DynamicInsert
@DynamicUpdate
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = CarAccident.CONST_TABLE_NAME)
public class CarAccident extends Model {
    public static final String CONST_TABLE_NAME = "ser_car_accident";
    @Id
    @Column(name = "id", nullable = false, length = 24)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "车险报案单", padding = 5, prefix = "BA%(company)%(yy)%(month)", useDateRange = true)
    @Comment("车险报案单号")
    private String id;

    @Column(name = "business_type_name", length = 64)
    @Comment("单据类型名称")
    private String businessTypeName = "车险报案单";

    @Column(name = "report_number", length = 64)
    @Comment("报案号")
    private String reportNumber;

    @Column(name = "phone_number", length = 16)
    @Comment("报案人电话号")
    private String phoneNumber;

    @Column(name = "third_party_phone", length = 16)
    @Comment("第三方电话")
    private String thirdPartyPhone;

    @Column(name = "report_person", length = 16)
    @Comment("报案人")
    private String reportPerson;

    @Column(name = "relation_Car", length = 64)
    @Comment("相关车辆")
    private String relationCar;

    @Column(name = "car_accident_place", length = 64)
    @Comment("出险地点")
    private String carAccidentPlace;

    @Column(name = "car_accident_describe", length = 256)
    @Comment("出险经过")
    private String carAccidentDescribe;

    @Column(name = "injured", length = 16)
    @Comment("受伤数")
    private Integer injured;

    @Column(name = "injured_state", columnDefinition = "number(1,0) default 0", nullable = false)
    @Comment("是否受伤")
    private boolean injuredState;

    public boolean isInjuredState(){
        return injured != null && injured > 0 ? true : injuredState;
    }

    public void setInjuredState(boolean injuredState){
        if (!injuredState) this.injured = 0;
        this.injuredState = injuredState;
    }

    @Column(name = "die", length = 16)
    @Comment("死亡数")
    private Integer die;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "car_accident_date", length = 32)
    @Comment("出险日期")
    private Date carAccidentDate;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "report_place", length = 32)
    @Comment("报案日期")
    private Date reportDate;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "track_date", length = 32)
    @Comment("跟踪时间")
    private Date trackDate;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "PICK_CAR_TIME", length = 32)
    @Comment("接车时间")
    private Date pickCarTime;

    @Column(name = "source_from", length = 16)
    @Comment("单据来源")
    private String sourceFrom;

    // @Column(name = "source_business_type", length = 32)
    // @Comment("来源单据类型")
    // private String sourceBusinessType;

    // @Column(name = "source_business_type_name", length = 64)
    // @Comment("来源单据类型名称")
    // private String sourceBusinessTypeName;

    @Column(name = "car_Number", length = 16)
    @Comment("车牌号码")
    private String carNumber;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "insurance_company_id", referencedColumnName = "id")
    @Comment("保险公司")
    private InsuranceCompany insuranceCompany;

    @Comment("会员扩展信息")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_expand_id", referencedColumnName = "id")
    private FnCustomerExpand customerExpand;

    @OneToMany(mappedBy = "carAccident", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<PickCarTypeAccident> typeAccidents = new ArrayList();

    public List<PickCarTypeAccident> getTypeAccidents() {
        if(typeAccidents == null) {
            return new  ArrayList();
        }
        for (PickCarTypeAccident item : typeAccidents) {
            // if("T1".equals(item.getPickUpType().getId()) && (item.getRemarks() == null || "".equals(item.getRemarks().trim()))){
            //     throw new RuntimeException("接车类型为其他，必须填写备注信息");
            // }
            item.setCarAccident(this);
        }
        return typeAccidents;
    }

    public void setTypeAccidents(List<PickCarTypeAccident> pickCarTypeAccidents){
        this.typeAccidents.clear();
        if (pickCarTypeAccidents != null) {
            this.typeAccidents.addAll(pickCarTypeAccidents);
        }
    }
    @Transient
    private Map customer;

    public Map getCustomer() {
        if (customerExpand == null || customerExpand.getMobile() == null){
            return null;
        }
        return MapUtil.mapper(
                "realname", customerExpand.getRealname(),
                "mobile", customerExpand.getMobile(),
                "level", customerExpand.getCustomerLevelId(),
                "vendorCode", customerExpand.getVendorCode(),
                "userRole", MapUtil.mapper(
                        "id", customerExpand.getUserRoleId(),
                        "name", customerExpand.getUserRoleName()
                )
        );
    }

    @Transient
    private Map customerCar;

    public Map getCustomerCar() {
        if (customerExpand == null || customerExpand.getCarLicense() == null){
            return null;
        }
        return MapUtil.mapper(
                "carLicense", customerExpand.getCarLicense(),
                "vendorCode", customerExpand.getVendorCode(),
                "customer", this.getCustomer(),
                "jekunModelCode", customerExpand.getJekunModelCode(),
                "carServiceLevel", StringUtils.isEmpty(customerExpand.getCarModelService())? "": "["+customerExpand.getCarModelService()+"]",
                "vin", customerExpand.getVin()
        );
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "dept_id", referencedColumnName = "id")
    @Comment("所属门店")
    private Dept dept;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "company_id", referencedColumnName = "id", nullable = false)
    @Comment("所属公司")
    private PartyRole company;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "staff_id", referencedColumnName = "id")
    @Comment("员工")
    private PartyRole staff;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "business_Staff", referencedColumnName = "id")
    @Comment("商务员工")
    private PartyRole businessStaff;


    @Comment("案件类型")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "case_type", referencedColumnName = "id")
    private Enumeration caseType;

    @Comment("水泡车")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "waterloggedCar", referencedColumnName = "id")
    private Enumeration waterloggedCar;

    @States(name = "事故类型", values = {
            @State(id = "A", name = "免现场"),
            @State(id = "B", name = "单方事故"),
            @State(id = "C", name = "多方事故")
    })
    @Comment("事故类型")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "accident_type", referencedColumnName = "id")
    private BusinessAttributeValue accidentType;

    @States(name = "出险类型", values = {
            @State(id = "1", name = "车损"),
            @State(id = "2", name = "盗抢"),
            @State(id = "3", name = "玻璃"),
            @State(id = "4", name = "划痕"),
            @State(id = "5", name = "自燃"),
            @State(id = "6", name = "其他")
    })
    @Comment("出险类型")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "danger_Type",  referencedColumnName = "id")
    private BusinessAttributeValue dangerType;

    @States(name = "本车责任", values = {
            @State(id = "1", name = "标的全责"),
            @State(id = "2", name = "主责"),
            @State(id = "3", name = "次责"),
            @State(id = "4", name = "第三者无责"),
            @State(id = "5", name = "同责")
    })
    @Comment("本车责任")
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "vehicle_Duty", referencedColumnName = "id")
    private BusinessAttributeValue vehicleDuty;

    @States(name = "单据状态", values = {
            @State(id = "create", name = "新增"),
            @State(id = "inStore", name = "已到店"),
            @State(id = "store", name = "转门店"),
            @State(id = "backStage", name = "转后台"),
            @State(id = "blacklist", name = "转黑名单"),
            @State(id = "transferBase", name = "转基地"),
            @State(id = "baseReported", name = "基地代报案"),
            @State(id = "fixedLoss", name = "转定损"),
            @State(id = "repeal", name = "终止")
    })
    @Column(name = "state", length = 32, nullable = false)
    @Comment("单据状态")
    private String state = "create";
    public String getStateName(String state){
        switch (state){
            case "create":
                return "新增";
            case "inStore":
                return "已到店";
            case "store":
                return "转门店";
            case "backStage":
                return "转后台";
            case "blacklist":
                return "转黑名单";
            case "transferBase":
                return "转基地";
            case "baseReported":
                return "基地代报案";
            case "fixedLoss":
                return "转定损";
            case "repeal":
                return "终止";
                default:
                    return "";
        }
    }

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "fixed_loss_Date")
    @Comment("转定损日期")
    private Date fixedLossDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "to_Store_Uid", referencedColumnName = "id")
    @Comment("转门店人")
    private PartyRole toStoreUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "to_Store_Date")
    @Comment("转门店日期")
    private Date toStoreDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "back_Stage_Uid", referencedColumnName = "id")
    @Comment("转后台人")
    private PartyRole backStageUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "back_Stage_Date")
    @Comment("转后台日期")
    private Date backStageDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "repeal_uid", referencedColumnName = "id")
    @Comment("终止人")
    private PartyRole repealUid;

    @JSONField(format = DateUtil.SHOW_DATETIME_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "repeal_date")
    @Comment("终止日期")
    private Date repealDate;


    @Column(name = "help_Reported", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    @Comment("代报案标识")
    private boolean helpReported = false;

    @Column(name = "repeal_Remarks", length = 256)
    @Comment("终止备注")
    private String repealRemarks;

    @Column(name = "APP_Order", length = 32)
    @Comment("APP订单")
    private String APPOrder;

    @Column(name = "history_order", length = 256)
    @Comment("历史单据")
    private String historyOrder;

    @Column(name = "append_Remarks", length = 256)
    @Comment("追加备注")
    private String appendRemarks;

    @Column(name = "apply_Remarks", length = 256)
    @Comment("协助申请备注")
    private String applyRemarks;

    @Column(name = "report_Note", length = 256)
    @Comment("总部协助完成汇报")
    private String reportNote;

    @File
    @Lob
    @Comment("三卡一证")
    @Basic(fetch = FetchType.LAZY)
    @Column(name = "three_Card", columnDefinition = "CLOB")
    private String threeCard;

    @File
    @Lob
    @Comment("事故照片")
    @Basic(fetch = FetchType.LAZY)
    @Column(name = "accident_Photos", columnDefinition = "CLOB")
    private String accidentPhotos;

    @OneToOne(mappedBy = "carAccident", cascade = CascadeType.ALL, orphanRemoval = true)
    private CarEvaluation carEvaluations;  //评估信息



    public CarEvaluation getCarEvaluations() {
        if (carEvaluations == null){
            return null;
        }
        carEvaluations.setCarAccident(this);
        return carEvaluations;
    }
    @Transient
    private PartyRole _creator;

    @Transient
    private String assistBaseID;

    public String getAssistBaseID() {
        if (Objects.isNull(carEvaluations) || Objects.isNull(carEvaluations.getBase()) ) {
            return null;
        }
        return carEvaluations.getBase().getBranch().getId();
    }

    @Transient
    public PartyRole get_creator() {
        if (this.getCreator() == null){
            return null;
        }
        return SpringManager.getBean(PartyRoleRepository.class).findOne(this.getCreator());
    }

    @Column(name ="risk_Car", columnDefinition = ApesConst.FIELD_BOOLEAN_FALSE)
    @Comment("定损风险车")
    private boolean riskCar = false;


    public static final  Map<String, Consumer<BusinessAttributeValue>> methodMap = new HashMap<>();
    {
        methodMap.put("accidentType", this::setAccidentType);
        methodMap.put("dangerType", this::setDangerType);
        methodMap.put("vehicleDuty", this::setVehicleDuty);
    };

}
